package com.tvserials.notification.parser;

import com.tvserials.notification.dto.Episode;
import com.tvserials.notification.dto.EpisodeMedia;
import com.tvserials.notification.dto.Serial;
import com.tvserials.notification.exceptions.NetworkConnectionException;
import com.tvserials.notification.exceptions.PageParseException;
import com.tvserials.notification.utils.VOUtils;
import com.tvserials.notification.vo.*;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * Created by Alex on 15.04.2014.
 */
public class NewStudioHtmlPageParser extends DefaultPageParser {

    public static final String MAIN_PAGE = "http://newstudio.tv";

    public List<Episode> parse(TvEpisodeFilterVO filterVO) throws NetworkConnectionException, PageParseException {
        Date latestSyncDate = filterVO.getLastSyncDate();
        List<Serial> allowedSerials = filterVO.getSerials();
        int startWith = (filterVO.getPageNo() - 1) * 50;
        try {
            Connection connect = Jsoup.connect(MAIN_PAGE + "/tracker.php?start=" + startWith);
            connect.timeout(PageParserFactory.TIMEOUT);
            connect.header("Accept-Language", "uk,ru;q=0.8,en-us;q=0.5,en;q=0.3");

            Document document = connect.get();
            Elements tableContent = document.select("tr.hl-tr");
            List<EpisodeMedia> episodeMedias = new ArrayList<EpisodeMedia>();
            for (Element element : tableContent) {
                String dateString = element.select("td.row4.small").text();
                Date pubDate = formatDate(dateString);
                String title = element.select("a.genmed").get(0).select("b").text();
                String showName = title.substring(0, title.indexOf("(")).trim();

                if (isSigned(allowedSerials, showName) && graterThan(latestSyncDate, pubDate)) {
                    String serialLogoUrl = element.select("img").get(0).attr("src");
                    String size = element.select("a.small.tr-dl").get(0).text();
                    String link = element.select("a.small.tr-dl").get(0).attr("href").replace("./", "/");

                    //extract media type from title and add to size
                    size = String.format("%s, %s", getFormatFromTitle(title), size);

                    EpisodeMedia episodeMedia = new EpisodeMedia();
                    episodeMedia.setSize(size);
                    episodeMedia.setTitle(title);
                    episodeMedia.setLink(MAIN_PAGE + link);
                    episodeMedia.setImageLink(MAIN_PAGE + serialLogoUrl);
                    episodeMedia.setPubDate(pubDate);
                    episodeMedias.add(episodeMedia);
                }
            }
            List<Episode> episodes = VOUtils.groupItems(episodeMedias);
            return episodes;
        } catch (IOException e) {
            throw new NetworkConnectionException(e.getMessage(), e);
        } catch (ParseException e) {
            throw new PageParseException(e);
        }
    }

    private boolean isSigned(List<Serial> allowedSerials, String showName) {
        return allowedSerials.contains(new Serial(showName, getSourceType()));
    }

    private String getFormatFromTitle(String title) {
        String format = "";
        if (title.contains("WEBDL")) {
            format = title.substring(title.indexOf("WEBDL"), title.length());
        } else if (title.contains("HDTV")) {
            format = title.substring(title.indexOf("HDTV"), title.length());
        }
        return format;
    }

    private Date formatDate(String str) throws ParseException {
        String dateStr = str.replace("Today", "").replace("Yesterday", "");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MMM-yy, hh:mm", Locale.ENGLISH);
        return simpleDateFormat.parse(dateStr);
    }

    @Override
    public List<Serial> parseSerialsList() throws NetworkConnectionException {

        try {
            Connection connect = Jsoup.connect(MAIN_PAGE + "/tracker.php?start=0");
            connect.timeout(PageParserFactory.TIMEOUT);
            connect.header("Accept-Language", "uk,ru;q=0.8,en-us;q=0.5,en;q=0.3");

            Document document = connect.get();
            Elements attributes = document.select("div.accordion").get(0).getElementsByAttributeValueMatching("href", "/");

            List<Serial> serials = new ArrayList<Serial>();
            for (Element element : attributes) {
                String title = element.text();
                String link = element.attr("href");

                Serial serial = new Serial();
                serial.setShowName(title);
                serial.setLink(MAIN_PAGE + link);
                serial.setSourceType(SourceType.NEW_STUDIO);
                serials.add(serial);
            }
            return serials;
        } catch (IOException e) {
            throw new NetworkConnectionException(e.getMessage(), e);
        }
    }

    @Override
    public SourceType getSourceType() {
        return SourceType.NEW_STUDIO;
    }
}
